package com.example.elasticsearch;

import com.example.elasticsearch.entity.Goods;
import com.example.elasticsearch.mapper.GoodsMapper;
import com.example.elasticsearch.mapper.GoodsRepository;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.range.ParsedDateRange;
import org.elasticsearch.search.aggregations.bucket.range.ParsedRange;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.ParsedMin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 必须添加类描述
 *
 * @author HTJT
 * @date 2023/3/7 15:11
 * @version 1.0
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class Bucket {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 根据商品分类聚合查询
     */
    @Test
    public void aggBucket() {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 聚合条件
        queryBuilder.addAggregation(AggregationBuilders.terms("aggCategoryName").field("categoryName").size(10));
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //查询,获取查询结果
        SearchHits<Goods> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Goods.class, IndexCoordinates.of("goods"));
        //获取聚合结果
        Aggregations aggregations = searchHits.getAggregations();
        assert aggregations != null;
        ParsedStringTerms aggCategoryName = aggregations.get("aggCategoryName");
        //打印聚合结果
        System.out.println(aggCategoryName.getBuckets());
        for (Terms.Bucket bucket : aggCategoryName.getBuckets()) {
            System.out.println(bucket.getKeyAsString() + "====" + bucket.getDocCount());

        }
    }

    /**
     * 根据价格区间分组查询
     */
    @Test
    public void aggRange() {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        queryBuilder.addAggregation(AggregationBuilders.range("priceRange").field("price").addUnboundedTo(1000).addRange(1000, 3000).addUnboundedFrom(3000));
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());

        SearchHits<Goods> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Goods.class, IndexCoordinates.of("goods"));

        // 获取聚合信息
        Aggregations aggregations = searchHits.getAggregations();
        assert aggregations != null;
        ParsedRange priceRange = aggregations.get("priceRange");

        //获取总记录数
        System.out.println("totalHits = " + searchHits.getTotalHits());

        //获取值返回
        for (Range.Bucket bucket : priceRange.getBuckets()) {
            System.out.println(bucket.getKeyAsString() + "====" + bucket.getDocCount());
        }
    }

    /**
     * 根据日期分组查询出商品创建日期在"2017-09" - "2017-10" 之间的数据
     */
    @Test
    public void aggDateRange() {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // range查询包左不包右,即:[1,10)
        queryBuilder.addAggregation(AggregationBuilders.dateRange("dateRange").field("createTime").format("yyy-MM").addRange("2017-09", "2017-10"));
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());

        SearchHits<Goods> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Goods.class, IndexCoordinates.of("goods"));

        // 获取聚合信息
        Aggregations aggregations = searchHits.getAggregations();
        assert aggregations != null;
        ParsedDateRange priceRange = aggregations.get("dateRange");

        //获取总记录数
        System.out.println("totalHits = " + searchHits.getTotalHits());

        //获取值返回
        for (Range.Bucket bucket : priceRange.getBuckets()) {
            System.out.println(bucket.getKeyAsString() + "====" + bucket.getDocCount());
        }
    }
}
